<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="16">
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-title">
                客户总数
              </div>
              <div class="stat-value">
                {{ stats.totalLeads }}
              </div>
              <div
                v-if="stats.leadsGrowth !== undefined"
                :class="['stat-change', stats.leadsGrowth >= 0 ? 'positive' : 'negative']"
              >
                <el-icon><TrendCharts /></el-icon>
                <span>{{ stats.leadsGrowth >= 0 ? '+' : '' }}{{ stats.leadsGrowth }}%</span>
              </div>
            </div>
            <el-icon
              class="stat-icon"
              :size="60"
              color="#1890ff"
            >
              <User />
            </el-icon>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-title">
                房源总数
              </div>
              <div class="stat-value">
                {{ stats.totalProperties }}
              </div>
              <div
                v-if="stats.propertiesGrowth !== undefined"
                :class="['stat-change', stats.propertiesGrowth >= 0 ? 'positive' : 'negative']"
              >
                <el-icon><TrendCharts /></el-icon>
                <span>{{ stats.propertiesGrowth >= 0 ? '+' : '' }}{{ stats.propertiesGrowth }}%</span>
              </div>
            </div>
            <el-icon
              class="stat-icon"
              :size="60"
              color="#52c41a"
            >
              <House />
            </el-icon>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-title">
                本月带看
              </div>
              <div class="stat-value">
                {{ stats.monthlyVisits }}
              </div>
              <div
                v-if="stats.visitsGrowth !== undefined"
                :class="['stat-change', stats.visitsGrowth >= 0 ? 'positive' : 'negative']"
              >
                <el-icon><TrendCharts /></el-icon>
                <span>{{ stats.visitsGrowth >= 0 ? '+' : '' }}{{ stats.visitsGrowth }}%</span>
              </div>
            </div>
            <el-icon
              class="stat-icon"
              :size="60"
              color="#faad14"
            >
              <Document />
            </el-icon>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <div class="stat-content">
            <div class="stat-info">
              <div class="stat-title">
                成交量
              </div>
              <div class="stat-value">
                {{ stats.deals }}
              </div>
              <div
                v-if="stats.dealsGrowth !== undefined"
                :class="['stat-change', stats.dealsGrowth >= 0 ? 'positive' : 'negative']"
              >
                <el-icon><TrendCharts /></el-icon>
                <span>{{ stats.dealsGrowth >= 0 ? '+' : '' }}{{ stats.dealsGrowth }}%</span>
              </div>
            </div>
            <el-icon
              class="stat-icon"
              :size="60"
              color="#f5222d"
            >
              <TrendCharts />
            </el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 今日优先跟进 (MVP1 新增) -->
    <el-row
      :gutter="16"
      style="margin-top: 16px"
    >
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>今日优先跟进 ({{ priorityLeads.total }})</span>
              <el-button
                size="small"
                type="primary"
                @click="refreshQualityScores"
                :loading="recalculating"
              >
                刷新评分
              </el-button>
            </div>
          </template>

          <el-empty
            v-if="!priorityLeads.leads || priorityLeads.leads.length === 0"
            description="暂无优先跟进客户"
            :image-size="80"
          />

          <el-table
            v-else
            :data="priorityLeads.leads"
            style="width: 100%"
            @row-click="handleLeadClick"
            class="priority-leads-table"
          >
            <el-table-column
              prop="name"
              label="客户姓名"
              width="120"
            />
            <el-table-column
              prop="phone"
              label="手机号"
              width="140"
            />
            <el-table-column
              label="质量等级"
              width="120"
              align="center"
            >
              <template #default="{ row }">
                <el-tag
                  :type="getQualityGradeType(row.quality_grade)"
                  effect="dark"
                  size="large"
                >
                  {{ row.quality_grade || 'N/A' }} 级
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="质量分数"
              width="120"
              align="center"
            >
              <template #default="{ row }">
                <el-progress
                  :percentage="row.quality_score || 0"
                  :color="getQualityScoreColor(row.quality_score)"
                  :stroke-width="16"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="需求类型"
              width="120"
            >
              <template #default="{ row }">
                {{ getDemandTypeLabel(row.demand_type) }}
              </template>
            </el-table-column>
            <el-table-column
              label="跟进阶段"
              width="120"
            >
              <template #default="{ row }">
                {{ getStageLabel(row.stage) }}
              </template>
            </el-table-column>
            <el-table-column
              label="未联系天数"
              width="120"
              align="center"
            >
              <template #default="{ row }">
                <el-tag
                  :type="getDaysUncontactedType(row.updated_at)"
                  size="large"
                >
                  {{ calculateDaysUncontacted(row.updated_at) }} 天
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="100"
              fixed="right"
            >
              <template #default="{ row }">
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="viewLead(row.id)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row
      :gutter="16"
      style="margin-top: 16px"
    >
      <!-- 访客单趋势 -->
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>访客单趋势</span>
              <el-radio-group
                v-model="visitorTrendPeriod"
                size="small"
              >
                <el-radio-button label="week">
                  近7天
                </el-radio-button>
                <el-radio-button label="month">
                  近30天
                </el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <VChart
            v-if="chartReady"
            :option="visitorTrendOption"
            style="height: 300px"
            autoresize
          />
        </el-card>
      </el-col>

      <!-- 房源状态分布 -->
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <span>房源状态分布</span>
          </template>
          <VChart
            v-if="chartReady"
            :option="propertyStatusOption"
            style="height: 300px"
            autoresize
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 经纪人排行榜 -->
    <el-row
      :gutter="16"
      style="margin-top: 16px"
    >
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <span>经纪人业绩排行</span>
          </template>
          <VChart
            v-if="chartReady"
            :option="agentRankingOption"
            style="height: 300px"
            autoresize
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'DashboardPage' })
/**
 * 数据看板页面
 *
 * Vue3 + ECharts 集成最佳实践:
 * 1. 使用 vue-echarts 组件
 * 2. 响应式图表配置
 * 3. 自动resize支持
 */
import { ref, computed, onMounted, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { statsApi } from '@/api/modules/stats'
import type { PriorityFollowupsResponse } from '@/api/modules/stats'

const router = useRouter()

// 异步加载图表组件，减少初始包体积
const chartReady = ref(false)
const VChart = defineAsyncComponent(async () => {
  const mod = await import('vue-echarts')
  return mod.default
})

// 在挂载阶段按需加载并注册 ECharts 组件
onMounted(async () => {
  const { use } = await import('echarts/core')
  const { CanvasRenderer } = await import('echarts/renderers')
  const { LineChart, PieChart, BarChart } = await import('echarts/charts')
  const { TitleComponent, TooltipComponent, LegendComponent, GridComponent } = await import(
    'echarts/components'
  )

  use([
    CanvasRenderer,
    LineChart,
    PieChart,
    BarChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent,
  ])

  // 动态导入图表配置生成函数，进入页面时再加载
  const opts = await import('./dashboard/options')
  getVisitorTrendOption = opts.getVisitorTrendOption
  getPropertyStatusOption = opts.getPropertyStatusOption
  getAgentRankingOption = opts.getAgentRankingOption

  chartReady.value = true
  // 加载统计数据
  await loadStats()
  // 加载优先跟进客户 (MVP1 新增)
  await loadPriorityFollowups()
})

// ========== 响应式数据 ==========
const stats = ref({
  totalLeads: 0,
  totalProperties: 0,
  monthlyVisits: 0,
  deals: 0,
  leadsGrowth: undefined as number | undefined,
  propertiesGrowth: undefined as number | undefined,
  visitsGrowth: undefined as number | undefined,
  dealsGrowth: undefined as number | undefined,
})

// 加载统计数据
const loadStats = async () => {
  try {
    let overviewData: any = await statsApi.getOverview()

    // 如果返回的是包装格式 {code, message, data}，提取data字段
    if (overviewData && 'data' in overviewData && 'code' in overviewData) {
      overviewData = overviewData.data
    }

    stats.value = {
      totalLeads: overviewData.total_leads || 0,
      totalProperties: overviewData.total_properties || 0,
      monthlyVisits: overviewData.monthly_visits || 0,
      deals: overviewData.closed_won || 0,
      leadsGrowth: undefined,
      propertiesGrowth: undefined,
      visitsGrowth: undefined,
      dealsGrowth: undefined,
    }
  } catch (error) {
    console.error('Failed to load stats:', error)
    // 保持默认值0
  }
}

import type { Period } from './dashboard/options'
const visitorTrendPeriod = ref<Period>('week')

// 动态配置函数（按需导入后赋值）
import type { EChartsOption } from 'echarts'
import type { PropertyStatusData, AgentRankingData } from './dashboard/options'
let getVisitorTrendOption: (period: 'week' | 'month', data: number[]) => EChartsOption
let getPropertyStatusOption: (data: PropertyStatusData[]) => EChartsOption
let getAgentRankingOption: (data: AgentRankingData[]) => EChartsOption

// ========== 图表数据 ==========
const visitorTrendData = ref<number[]>([])
const propertyStatusData = ref<PropertyStatusData[]>([])
const agentRankingData = ref<AgentRankingData[]>([])

// 查看客户详情
const viewLead = (leadId: number) => {
  router.push(`/leads/${leadId}`)
}

// ========== 今日优先跟进 (MVP1 新增) ==========
const priorityLeads = ref<PriorityFollowupsResponse>({
  total: 0,
  leads: []
})

const recalculating = ref(false)

// 加载优先跟进客户
const loadPriorityFollowups = async () => {
  try {
    const response = await statsApi.getPriorityFollowups(10)
    // 确保响应数据格式正确，防止 undefined 破坏结构
    if (response && typeof response === 'object' && 'leads' in response) {
      priorityLeads.value = response
    } else {
      console.warn('Invalid priority followups response format:', response)
      priorityLeads.value = { total: 0, leads: [] }
    }
  } catch (error) {
    console.error('Failed to load priority followups:', error)
    // 失败时重置为默认值
    priorityLeads.value = { total: 0, leads: [] }
  }
}

// 刷新质量评分
const refreshQualityScores = async () => {
  try {
    recalculating.value = true
    const result = await statsApi.recalculateQualityScores(100)
    ElMessage.success(result.message || '评分已更新')
    // 刷新优先跟进列表
    await loadPriorityFollowups()
  } catch (error) {
    ElMessage.error('刷新评分失败')
    console.error('Failed to recalculate quality scores:', error)
  } finally {
    recalculating.value = false
  }
}

// 点击行查看客户详情
const handleLeadClick = (row: any) => {
  viewLead(row.id)
}

// 获取质量等级对应的标签类型
const getQualityGradeType = (grade: string | null) => {
  if (!grade) return 'info'
  switch (grade.toUpperCase()) {
    case 'S':
      return 'danger' // 红色 - 最高优先级
    case 'A':
      return 'warning' // 橙色 - 高优先级
    case 'B':
      return 'success' // 绿色 - 中等优先级
    case 'C':
      return 'primary' // 蓝色 - 常规
    case 'D':
      return 'info' // 灰色 - 低优先级
    default:
      return 'info'
  }
}

// 获取质量分数对应的进度条颜色
const getQualityScoreColor = (score: number | null) => {
  if (!score) return '#909399'
  if (score >= 90) return '#f56c6c' // S级 - 红色
  if (score >= 80) return '#e6a23c' // A级 - 橙色
  if (score >= 70) return '#67c23a' // B级 - 绿色
  if (score >= 60) return '#409eff' // C级 - 蓝色
  return '#909399' // D级 - 灰色
}

// 获取需求类型标签
const getDemandTypeLabel = (demandType: string | null) => {
  if (!demandType) return '-'
  const labels: Record<string, string> = {
    rent_whole: '整租',
    rent_shared: '合租',
    rent_short: '短租',
    buy: '买房',
    sell: '卖房'
  }
  return labels[demandType] || demandType
}

// 获取跟进阶段标签
const getStageLabel = (stage: string | null) => {
  if (!stage) return '-'
  const labels: Record<string, string> = {
    new: '新客户',
    contacted: '已联系',
    viewing: '看房中',
    negotiating: '协商中',
    closed_won: '已成交',
    closed_lost: '已流失'
  }
  return labels[stage] || stage
}

// 计算未联系天数
const calculateDaysUncontacted = (updatedAt: string | null) => {
  if (!updatedAt) return 0
  const now = new Date()
  const updated = new Date(updatedAt)
  const diffTime = Math.abs(now.getTime() - updated.getTime())
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 获取未联系天数标签类型
const getDaysUncontactedType = (updatedAt: string | null) => {
  const days = calculateDaysUncontacted(updatedAt)
  if (days >= 7) return 'danger'
  if (days >= 5) return 'warning'
  if (days >= 3) return 'primary'
  return 'success'
}

// ========== 图表配置 ==========

// 访客单趋势（按需生成配置）
const visitorTrendOption = computed<EChartsOption | Record<string, never>>(() =>
  chartReady.value && getVisitorTrendOption ? getVisitorTrendOption(visitorTrendPeriod.value, visitorTrendData.value) : {}
)

// 房源状态分布（按需生成配置）
const propertyStatusOption = computed<EChartsOption | Record<string, never>>(() =>
  chartReady.value && getPropertyStatusOption ? getPropertyStatusOption(propertyStatusData.value) : {}
)

// 经纪人排行（按需生成配置）
const agentRankingOption = computed<EChartsOption | Record<string, never>>(() =>
  chartReady.value && getAgentRankingOption ? getAgentRankingOption(agentRankingData.value) : {}
)
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.stat-change {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.stat-change.positive {
  color: #52c41a;
}

.stat-change.negative {
  color: #f5222d;
}

.stat-icon {
  opacity: 0.15;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 今日待办样式 */
.task-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.task-info {
  flex: 1;
}

.task-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.trigger-reason {
  color: #f56c6c;
  font-weight: bold;
  margin: 4px 0;
  font-size: 14px;
}

.task-notes {
  color: #909399;
  font-size: 13px;
  margin: 4px 0;
  line-height: 1.5;
}

.task-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

/* 优先跟进客户表格样式 (MVP1 新增) */
.priority-leads-table {
  cursor: pointer;
}

.priority-leads-table :deep(.el-table__row) {
  cursor: pointer;
  transition: background-color 0.2s;
}

.priority-leads-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
